import { createAxios } from '@/utils/http/axios';
import { ResultPage } from '#/axios';
import { getToken } from '@/utils/auth';

enum Api {
  pageGetProduct = '/tbuser/iotProduct/selectList',
}

export interface Product {
  id: string;
  name: string;
  productKey: string;
}

export function pageGetProductApi(data: {
  pageNum: number;
  pageSize: number;
  typeId?: string;
}): Promise<ResultPage<Product>> {
  return createAxios({
    requestOptions: {
      apiUrl: '/hc-api',
    },
  }).get(
    {
      url: Api.pageGetProduct,
      params: data,
    },
    {
      retryRequest: {
        isOpenRetry: true,
        count: 5,
        waitTime: 1000,
      },
    },
  );
}

export function exportAllProductApi() {
  const token = getToken();
  fetch('/hc-api' + Api.exportAllDevice, {
    method: 'POST',
    headers: [
      ['ContentType', 'application/json;charset=UTF-8'],
      ['Authorization', token],
    ],
  })
    .then(function (response: Response) {
      return response.blob();
    })
    .then(function (blob) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click();
      // 释放的 URL 对象以及移除 a 标签
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    });
}

export function excel2AddAllProduct(
  url: string,
  params: UploadFileParams,
  onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
) {
  return defHttp.uploadFile<UploadApiResult>(
    {
      url: '/hc-api' + Api.excel2AddJson,
      onUploadProgress,
    },
    params,
  );
}
